package com.fysports.framework.render;

import com.jfinal.ext.kit.RequestWarpper;
import com.jfinal.log.Log;
import com.jfinal.render.RenderFactory;
import com.fysports.web.module.breadcrumb.BreadcrumbModule;
import com.fysports.web.module.core.IModule;
import com.fysports.web.module.menu.RoleMenuModule;
import com.fysports.web.module.view.JsonView;
import com.fysports.web.module.view.OperateType;


/**
 * 替换系统系统默认的错误页面render
 * me.setError404View("/WEB-INF/template/404.ftl");
 * me.setError500View("/WEB-INF/template/500.ftl");
 * me.setErrorRenderFactory(new IErrorRenderFactory() {
 *
 * @Override public Render getRender(int errorCode, String view) {
 * return new AppErrorRender(errorCode,view);
 * }
 * });
 * Created by konbluesky
 * Date : 14-8-20 下午1:38
 * Project : JdmData_WebServer
 */
public class ErrorRender extends com.jfinal.render.ErrorRender {
    private static Log log = Log.getLog(ErrorRender.class);

    public ErrorRender(int errorCode, String view) {
        super(errorCode, view);
    }


    @Override public void render() {
        /*
        *   将异常从Request中取出;
        * */
        //        Exception req_exp=(Exception)request.getAttribute(AppMainRenderFactory.RENDER_ERROR_EXP);
        //        String errMsg= StringKit.FormatStackTrace(req_exp);
        //        request.setAttribute("render_error_msg",errMsg);

        //判断是否ajax请求

        if (new RequestWarpper(request).isAjax()) {

            JsonView jv = new JsonView();
            jv.setStatus(false);
            jv.setMsg("[AppErrorRender]" + OperateType.OPERATE_FAIL.getStrVal());

            RenderFactory.me().getJsonRender(jv.toJson()).setContext(request, response).render();

        }
        else {

            String view = getView();
            //出错时需要渲染左侧菜单
            IModule leftmenu = new RoleMenuModule(request);
            IModule breadview = new BreadcrumbModule(request);
            try {
                leftmenu.execute();
                breadview.execute();
            }
            catch (Exception e) {
                log.error("AppErrorRender has error!", e);
            }

            if (view != null) {
                RenderFactory.me().getRender(view).setContext(request, response).render();
                return;
            }
        }

    }


    public String getView() { // 覆盖父类 getView()
        if (errorCode == 404) {
            view = "/WEB-INF/template/404.ftl";
        }
        else if (errorCode == 500) {
            view = "/WEB-INF/template/500.ftl";
        }
        return view;
    }
}
